import { ts, pad } from '../utils'

/**
 * Removes empty lines and indent by two spaces to match the rest of the file.
 */
function normalizeLines(code: string) {
  return (
    code
      .split('\n')
      // FIXME: the code should be cleaned up by the codegen functions. Removing empty lines here
      // reduces readability of the route file info map.
      .filter((line) => line.length !== 0)
      .map((line) => pad(2, line))
      .join('\n')
  )
}

export function generateDTS({
  routesModule,
  routeNamedMap,
  routeFileInfoMap,
  paramsTypesDeclaration,
  customParamsType,
}: {
  routesModule: string
  routeNamedMap: string
  routeFileInfoMap: string
  paramsTypesDeclaration: string
  customParamsType: string
}) {
  return ts`
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection ES6UnusedImports
// Generated by unplugin-vue-router. !! DO NOT MODIFY THIS FILE !!
// It's recommended to commit this file.
// Make sure to add this file to your tsconfig.json file as an "includes" or "files" entry.

${
  paramsTypesDeclaration
    ? `
// Custom route params parsers
${paramsTypesDeclaration}

`.trimStart()
    : ''
}declare module 'vue-router/auto-resolver' {
  export type ParamParserCustom = ${customParamsType}
}

declare module '${routesModule}' {
  import type {
    RouteRecordInfo,
    ParamValue,
    ParamValueOneOrMore,
    ParamValueZeroOrMore,
    ParamValueZeroOrOne,
  } from 'vue-router'

  /**
   * Route name map generated by unplugin-vue-router
   */
${normalizeLines(routeNamedMap)}

  /**
   * Route file to route info map by unplugin-vue-router.
   * Used by the \`sfc-typed-router\` Volar plugin to automatically type \`useRoute()\`.
   *
   * Each key is a file path relative to the project root with 2 properties:
   * - routes: union of route names of the possible routes when in this page (passed to useRoute<...>())
   * - views: names of nested views (can be passed to <RouterView name="...">)
   *
   * @internal
   */
${normalizeLines(routeFileInfoMap)}

  /**
   * Get a union of possible route names in a certain route component file.
   * Used by the \`sfc-typed-router\` Volar plugin to automatically type \`useRoute()\`.
   *
   * @internal
   */
  export type _RouteNamesForFilePath<FilePath extends string> =
    _RouteFileInfoMap extends Record<FilePath, infer Info>
      ? Info['routes']
      : keyof RouteNamedMap
}
`.trimStart()
}
